package com.topnav.mc.admin.security.jwt.handle;

import com.alibaba.fastjson2.JSON;
import com.js.lib.exception.CustomException;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.uitls.ErrorResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 说明：
 * @类名: LoginFailureHandler
 * <p>
 *	登录失败处理
 * </p>
 * @author   kenny
 * @Date	 2022年2月11日上午10:59:34
 */
@Component
@Slf4j
public class LoginFailureHandler implements AuthenticationFailureHandler{
	@Override
	public void onAuthenticationFailure(
			HttpServletRequest request,
			HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		//log.error("认证：{}",exception);
		String json=null;
		if (exception.getCause() instanceof CustomException){
			json = JSON.toJSONString(
	        		ErrorResultUtil.result((CustomException)exception.getCause()));
		}else{
			json =  JSON.toJSONString(ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_LOGIN_FAILE));
		}
    	log.error(json);

        // 允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        response.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(json);

	}

}
